/*
  二次封装axios
*/

import axios from 'axios'
import { ERR_TIMEOUT, Options } from 'api/config'
import { changeFormData, timeOutAction } from 'common/js/utils'

// axios Get方式
export const ajaxGet = (url, params = {}, data = {}, option) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url,
      params,
      data,
      ...Options(),
      ...option
    }).then((res) => {
      if (res.data.code === ERR_TIMEOUT) {
        resolve(false)
        timeOutAction()
      } else {
        resolve(res.data)
      }
    }).catch((res) => {
      resolve(res)
    })
  })
}

// axios Post方式
export const ajaxPost = (url, data = {}, option) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url,
      data,
      ...Options(),
      ...option
    }).then((res) => {
      if (res.data.code === ERR_TIMEOUT) {
        resolve(false)
        timeOutAction()
      } else {
        resolve(res.data)
      }
    }).catch((res) => {
      resolve(res)
    })
  })
}

// axios Post FormData方式
export const ajaxPostFormData = (url, data = {}, option) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url,
      data: changeFormData(data),
      ...Options(),
      ...option
    }).then((res) => {
      if (res.data.code === ERR_TIMEOUT) {
        resolve(false)
        timeOutAction()
      } else {
        resolve(res.data)
      }
    }).catch((res) => {
      resolve(res)
    })
  })
}
